﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Hyt.Core.Security
{
    /// <summary>
    /// 安全主体解析器
    /// </summary>
    public class PrincipalResolver : IPrincipalResolver
    {
        private readonly List<ICustomPrincipalResolver> _resolvers=new List<ICustomPrincipalResolver>();

        public void AddResolver(ICustomPrincipalResolver resolver)
        {
            if (!_resolvers.Contains(resolver))
            {
                _resolvers.Add(resolver);
            }
        }

        public void RemoveResolver(ICustomPrincipalResolver resolver)
        {
            if (_resolvers.Contains(resolver))
            {
                _resolvers.Remove(resolver);
            }
        }

        public IPrincipal GetPrincipal(string principalid)
        {
            if (string.IsNullOrWhiteSpace(principalid))
            {
                return Principal.Anonymous;
            }
            string[] arr = principalid.Split(':');
            if (arr.Length != 2)
            {
                return Principal.Anonymous;
            }
            var resolver = _resolvers.FirstOrDefault(t => t.CanResolver(arr[0].Trim()));
            if (resolver == null)
            {
                return Principal.Anonymous;
            }
            return resolver.GetPrincipal(arr[0].Trim(),arr[1].Trim());
        }


        public string GetPrincipalString(IPrincipal principal)
        {
            if (principal==null||principal == Principal.Anonymous)
            {
                return "Anonymous";
            }
            return principal.GetPrincipalType() + ":" + principal.GetPrincipalId();
        }
    }
}
